package com.sgcc.pda.data.dao.impl;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.sgcc.pda.data.dao.ContentProviderDao;
import com.sgcc.pda.data.entity.base.AppInfo;
import com.sgcc.pda.data.entity.base.BehaviorTrajectoryInfo;
import com.sgcc.pda.data.entity.base.ExceptionInfo;
import com.sgcc.pda.data.entity.base.RegisterInfo;
import com.sgcc.pda.data.entity.base.SharepreferenceInfo;
import com.sgcc.pda.sdk.entity.BaseTaskInfo;

import com.sgcc.pda.util.ContentProviderUtil;
import com.sgcc.pda.util.DataConversionUtil;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 内容管理者数据库实现类.
 *
 * @author 王沛栋
 * @data 2018/1/19 14:18
 */

@SuppressWarnings({"StatementWithEmptyBody", "UnusedAssignment"})
public class ContentProviderDaoImpl implements ContentProviderDao {

    private static ContentProviderDaoImpl contentProviderDao;

    public static ContentProviderDaoImpl getInstance() {
        if (contentProviderDao == null) {
            contentProviderDao = new ContentProviderDaoImpl();
        }
        return contentProviderDao;
    }

    private ContentProviderDaoImpl() {
    }

    public void init(String contentProviderConnect) {
        CONTENT_PROVIDER_CONNECT = contentProviderConnect;
    }

    String CONTENT_PROVIDER_CONNECT;

    private static final String BEHAVIOR_TRAJECTORY_INFO = "BEHAVIOR_TRAJECTORY_INFO";//用户行为轨迹

    private static final String LOGIN_ = "LOGIN_";
    private static final String LOGIN_UID = "LOGIN_UID";
    private static final String USERCODE = "usercode";
    private static final String LOGININFO = "loginInfo";//保存登录所需信息
    private static final String DEPT_CODE = "DEPT_CODE";//部门编码
    private static final String THINTA_COMM = "thinta_comm";
    private static final String COMM_USBEnable = "comm_usbenable";
    private static final String COMM_IP = "comm_ip";//IP地址
    private static final String COMM_PORT = "comm_port";//端口号
    private static final String COMM_IP_USB = "comm_ip_usb";//USB通信方式IP地址
    private static final String COMM_PORT_USB = "comm_port_usb";//USB通信方式端口号


    private static final String TABLE_SHAREPREFERENCE_INFO = "SHAREPREFERENCE_INFO";
    private static final String TABLE_EXCEPTION_INFO = "EXCEPTION_INFO";
    private static final String TABLE_APP_INFO = "APP_INFO";
    private static final String TABLE_REGISTER_INFO = "REGISTER_INFO";
    private static final String TABLE_KNOWS_INFO = "KNOWS_INFO";
    private static final String UPDATE_APP_BASE_INFO_APK_APPUPDATA = "UPDATE_APP_BASE_INFO_APK_APPUPDATA";//查找注册信息
    private static final String BASE_TASK_INFO = "BASE_TASK_INFO";//基础工单表
    private static final String WATER_MARK_INFO = "water_mark_info";//文本水印信息

    /**
     * sp类型——boolean类型false
     */
    private static final String SP_TYPE_BOOLEAN_FALSE = "0";

    /**
     * sp类型——boolean类型true
     */
    private static final String SP_TYPE_BOOLEAN_TRUE = "1";


    /**
     * 存储类型boolean
     */
    private static final Map<String, Boolean> SP_TYPE_BOOLEAN = new HashMap<>();

    static {
        SP_TYPE_BOOLEAN.put(SP_TYPE_BOOLEAN_FALSE, false);
        SP_TYPE_BOOLEAN.put(SP_TYPE_BOOLEAN_TRUE, false);
    }


    @Override
    public void setSharepreference(Context context, SharepreferenceInfo info) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_SHAREPREFERENCE_INFO);
        //通过反射  将实体类转成ContentValues
        ContentValues values = DataConversionUtil.BeanToContentValues(info);
        resolver.insert(uri, values);
    }

    /**
     * 获取data应用定义的sp数据——String类型
     *
     * @param context
     * @param key
     * @return
     */
    @Override
    public String getSharepreferenceValue(Context context, String editKey, String key) {
        String result = null;
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_SHAREPREFERENCE_INFO);

        Cursor cursor = null;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, null, null, new String[]{key, editKey}, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
        }

        if (null == cursor) {
            return null;
        }


        while (cursor.moveToNext()) {
            result = cursor.getString(0);

        }
        cursor.close();
        return result;
    }


    /**
     * 获取data应用定义的sp数据——boolean类型
     *
     * @param context
     * @param key
     * @return
     */
    @Override
    public boolean getSharepreferenceBooleanValue(Context context, String editKey, String key) {
        String result = null;
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_SHAREPREFERENCE_INFO);

        Cursor cursor;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, null, null, new String[]{key, editKey}, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
            return false;
        }
        if (null == cursor) {
            return false;
        }

        while (cursor.moveToNext()) {
            result = cursor.getString(0);

        }
        cursor.close();

        return !TextUtils.isEmpty(result) && SP_TYPE_BOOLEAN.get(result);

    }

    @Override
    public void saveExceptionInfo(Context context, ExceptionInfo obj) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_EXCEPTION_INFO);
        //通过反射  将实体类转成ContentValues
        ContentValues values = DataConversionUtil.BeanToContentValues(obj);
        resolver.insert(uri, values);
    }

    @Override
    public List<AppInfo> getAppInfoListNeededInstall(Context context) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_APP_INFO);

        Cursor cursor;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, null, null, null, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
            return null;
        }
        if (null == cursor) {
            return null;
        }
        List<AppInfo> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            AppInfo info = new AppInfo();

            info.setAppIcon(cursor.getString(cursor.getColumnIndex("APP_ICON")));
            info.setAppIconLoc(cursor.getBlob(cursor.getColumnIndex("APP_ICON_LOC")));
            info.setAppName(cursor.getString(cursor.getColumnIndex("APP_NAME")));
            info.setAppShowNum(cursor.getInt(cursor.getColumnIndex("APP_SHOW_NUM")));
            info.setAssetsPath(cursor.getString(cursor.getColumnIndex("ASSETS_PATH")));
            info.setFilePath(cursor.getString(cursor.getColumnIndex("FILE_PATH")));
            info.setPackageName(cursor.getString(cursor.getColumnIndex("PACKAGE_NAME")));
            list.add(info);
        }
        cursor.close();

        return list;
    }

    @Override
    public List<RegisterInfo> getRegisterInfoList(Context context, String keyValue) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_REGISTER_INFO);

        Cursor cursor;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, null, null, new String[]{keyValue}, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
            return null;
        }
        if (null == cursor) {
            return null;
        }
        List<RegisterInfo> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            RegisterInfo info = new RegisterInfo();
            info.setCODE_CIPHER(cursor.getString(cursor.getColumnIndex("CODE_CIPHER")));
            info.setMAC(cursor.getString(cursor.getColumnIndex("MAC")));
            info.setOPT_CODE(cursor.getString(cursor.getColumnIndex("OPT_CODE")));
            info.setREG_IDX(cursor.getString(cursor.getColumnIndex("REG_IDX")));
            info.setRandomM(cursor.getString(cursor.getColumnIndex("RandomM")));
            list.add(info);
        }
        cursor.close();

        return list;
    }

    @Override
    public List<String> getKnowsInfoResonNames(Context context) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + TABLE_KNOWS_INFO);

        Cursor cursor;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, new String[]{"RSON_NAME"}, "where ABN_TYPE =? ", new String[]{"4001"}, "RSON_CODE");
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
            return null;
        }
        if (null == cursor) {
            return null;
        }
        List<String> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String rson_name = cursor.getString(cursor.getColumnIndex("RSON_NAME"));
            list.add(rson_name);
        }
        cursor.close();
        return list;
    }

    @Override
    public boolean saveAddOrUpdateAppBaseInfoState(Context context, String packageName, String addUpData) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + UPDATE_APP_BASE_INFO_APK_APPUPDATA);
        ContentValues values = new ContentValues();
        values.put("INTENT_ID", "test");
        int result = resolver.update(uri, values, null, new String[]{packageName, addUpData});
        if (result == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<BaseTaskInfo> getBaseTaskInfoList(Context context, String[] selectArgs) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + BASE_TASK_INFO);

        Cursor cursor;
        try {
            //获取表中所有记录
            cursor = resolver.query(uri, null, null, selectArgs, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl", "获取cursor报错");
            return null;
        }

        if (null == cursor) {
            return null;
        }

        List<BaseTaskInfo> list = DataConversionUtil.cursor2VOList(cursor, BaseTaskInfo.class);
        cursor.close();
        return list;
    }


    /**
     * 获取登录UID信息
     *
     * @return uid, userCode, deptCode, ip, port
     */
    public List<String> getLoginInfo(Context context) {
        List<String> datas = new ArrayList<>();
        String uid = ContentProviderUtil.getSharepreferenceValue(context, LOGIN_, LOGIN_UID);
        String userCode = ContentProviderUtil.getSharepreferenceValue(context, USERCODE, USERCODE);
        String deptCode = ContentProviderUtil.getSharepreferenceValue(context, LOGININFO, DEPT_CODE);
        String ip, port;
        if (ContentProviderUtil.getSharepreferenceBooleanValue(context, THINTA_COMM, COMM_USBEnable)) {
            ip = ContentProviderUtil.getSharepreferenceValue(context, THINTA_COMM, COMM_IP_USB);
            port = ContentProviderUtil.getSharepreferenceValue(context, THINTA_COMM, COMM_PORT_USB);
        } else {
            ip = ContentProviderUtil.getSharepreferenceValue(context, THINTA_COMM, COMM_IP);
            port = ContentProviderUtil.getSharepreferenceValue(context, THINTA_COMM, COMM_PORT);
        }
        datas.add(uid);
        datas.add(userCode);
        datas.add(deptCode);
        datas.add(ip);
        datas.add(port);
        return datas;
    }

    @Override
    public void saveBehaviorTrajectoryInfoContext(Context context, BehaviorTrajectoryInfo behaviorTrajectoryInfo) {
        ContentResolver resolver = context.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + BEHAVIOR_TRAJECTORY_INFO);
        //通过反射  将实体类转成ContentValues
        ContentValues values = DataConversionUtil.BeanToContentValues(behaviorTrajectoryInfo);

        if (null == values) {
        } else {
            resolver.insert(uri, values);
        }
    }

    @Override
    public void deleteBehaviorTrajectoryInfo(Context mContext, String businessIdentification, String sonBusinessIdentification) {
        ContentResolver resolver = mContext.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + BEHAVIOR_TRAJECTORY_INFO);
        resolver.delete(uri, null, new String[]{businessIdentification, sonBusinessIdentification});
    }

    @Override
    public boolean updateBehaviorTrajectoryInfo(Context mContext, String id) {
        ContentResolver resolver = mContext.getContentResolver();
        //定义要访问的ContentProvider的
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + BEHAVIOR_TRAJECTORY_INFO);
        ContentValues values = new ContentValues();
        values.put("INTENT_ID", "test");
        int result = resolver.update(uri, values, null, new String[]{id});
        if (result == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ArrayList<BehaviorTrajectoryInfo> getBehaviorTrajectoryInfo(Context context, String businessIdentification, String sonBusinessIdentification) {

        ContentResolver contentResolver = context.getContentResolver();
        Uri uri = Uri.parse(CONTENT_PROVIDER_CONNECT + BEHAVIOR_TRAJECTORY_INFO);
        Cursor cursor = null;

        try {
            //获取表中所有记录
            cursor = contentResolver.query(uri, null, null, new String[]{businessIdentification, sonBusinessIdentification}, null);
        } catch (Exception e) {
            //LogUtil.e("ContentProviderDaoImpl","获取cursor报错");
            return null;
        }
        if (null == cursor) {
            return null;
        }
        ArrayList<BehaviorTrajectoryInfo> behaviorTrajectoryInfoList = new ArrayList<>();
        BehaviorTrajectoryInfo info = null;
        while (cursor.moveToNext()) {
            info = new BehaviorTrajectoryInfo();
            info.setId(cursor.getLong(cursor.getColumnIndex("id")));
            info.setBusinessIdentification(cursor.getString(cursor.getColumnIndex("businessIdentification")));
            info.setSonBusinessIdentification(cursor.getString(cursor.getColumnIndex("sonBusinessIdentification")));
            info.setContent(cursor.getString(cursor.getColumnIndex("content")));
            info.setState(cursor.getString(cursor.getColumnIndex("state")));
            info.setInsertionTime(cursor.getString(cursor.getColumnIndex("insertionTime")));
            behaviorTrajectoryInfoList.add(info);
        }
        cursor.close();
        return behaviorTrajectoryInfoList;
    }

    /**
     * 获取文本水印信息
     *
     * @param context
     * @return userCode, deptCode, ip
     */
    public List<String> getWaterMarkInfo(Context context) {
        try {
            String info = ContentProviderUtil.getSharepreferenceValue(context, LOGININFO, WATER_MARK_INFO);
            if (!TextUtils.isEmpty(info)) {
                return Arrays.asList(info.split(","));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }


}


